package cn.wit.summit.chwan.ui.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bigkoo.convenientbanner.ConvenientBanner;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.adapters.GameLibraryTopAdapter;
import cn.wit.summit.chwan.adapters.RecommendV2Adapter;
import cn.wit.summit.chwan.interfaces.ScrollHeightListener;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.dto.JumpBaseBean;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.response.GameLibraryV3Response;
import cn.wit.summit.chwan.models.response.IndexBeanV2Response;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.base.BaseFragment;
import cn.wit.summit.chwan.ui.base.MyApplication;
import cn.wit.summit.chwan.utils.AccountBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.widgets.DownloadViewStrokeV2Big;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnRefreshListener;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/9/6.
 */

public class GameLibraryOneFragment extends BaseFragment {

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private int pn = 1;
    private LinearLayoutManager layoutManager;
    private RecommendV2Adapter adapter;
    private List<RecommendV2Adapter.ViewBean> viewBeans = new ArrayList<>();

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    private IndexBeanV2Response recomend_info;
    private List<JumpBaseBean> banner;
    private ScrollHeightListener listener;
    private int totalDy = 0;
    private ViewPager viewPager;
    private GameLibraryTopAdapter mAdapter;
    private JumpBaseBean banner_ad;

    public static GameLibraryOneFragment newInstance(ScrollHeightListener listener
            , GameLibraryTopAdapter mAdapter, ViewPager viewPager, List<JumpBaseBean> banner, IndexBeanV2Response recomend_info, JumpBaseBean banner_ad) {
        GameLibraryOneFragment temp = new GameLibraryOneFragment();
        temp.recomend_info = recomend_info;
        temp.banner_ad = banner_ad;
        temp.banner = banner;
        temp.listener = listener;
        temp.viewPager = viewPager;
        temp.mAdapter = mAdapter;
        return temp;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_game_library_one, container, false);
        ButterKnife.bind(this, view);

        retrofitManager = RetrofitManager.getInstance(getActivity());
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);

        initListView();
        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getActivity()!=null && isVisibleToUser && viewBeans.size()==0) {
            updataUi(recomend_info, banner_ad);
            pn += 1;
            if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this);//订阅
            }
        }
        if (!isVisibleToUser) {
            stopBannerPo();
        } else {
            initBannerPo();
        }
    }

    public void stopBannerPo() {
        if (layoutManager==null) return;
        View view = layoutManager.findViewByPosition(0);
        if (view==null) return;
        ConvenientBanner vp_recommend = view.findViewById(R.id.vp_recommend);
        if (vp_recommend!=null) {
            vp_recommend.stopTurning();
        }
    }

    public void initBannerPo() {
        if (layoutManager==null) return;
        View view = layoutManager.findViewByPosition(0);
        if (view==null) return;
        ConvenientBanner vp_recommend = view.findViewById(R.id.vp_recommend);
        if (vp_recommend!=null) {
            vp_recommend.setCurrentItem(MyApplication.bannerPo, false);
            vp_recommend.startTurning(4000-(System.currentTimeMillis() - MyApplication.bannerTime));
        }
    }

    private void initListView() {
        listener.OnScroll(0, totalDy, 0);

        layoutManager = new LinearLayoutManager(getContext()) {
            @Override
            public boolean canScrollVertically() {
                return true;
            }
        };

        adapter = new RecommendV2Adapter(getActivity(), viewBeans, viewPager, mAdapter);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getIndexDataForFirst();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                getIndexData();
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//                if (newState==0) {
//                    Fresco.getImagePipeline().resume();
//                } else {
//                    Fresco.getImagePipeline().pause();
//                }
//            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                totalDy += dy;
                listener.OnScroll(0, totalDy, dy);
            }
        });
    }

    private RefreshLayout mRefreshLayout;
    public void onRefresh(RefreshLayout refreshLayout) {
        this.mRefreshLayout = refreshLayout;
        getIndexDataForFirst();
    }

    public void onLoadMore(final RefreshLayout refreshLayout) {
        if (pn == 1) pn += 1;
        getIndexData();
    }

    private void getIndexDataForFirst() {
        refreshLayout.setEnableLoadMore(true);
        pn = 1;
        getIndexData();
    }

    private void getIndexData() {
        int uId = 0;
        AccountBean accountBean = AccountUtil.getInstance().getAccountData();
        if (accountBean != null) {
            uId = AccountUtil.getInstance().getUid();
        }

        api.getGameLibraryV3(uId, pn, pn==1 ? 0 : 1).enqueue(new MyCallback<ResponseBase<GameLibraryV3Response>>() {
            @Override
            public void onSuccess(ResponseBase<GameLibraryV3Response> model) {
                GameLibraryV3Response data = model.getData_info();
                if (data != null) {
                    updataUi(data.getRecommend_info(), data.getBanner_ad());
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                showToast(msg);
                refreshLayout.finishLoadMore();
            }
        });
    }

    private void updataUi(IndexBeanV2Response data, JumpBaseBean banner_ad) {
        if (mRefreshLayout!=null)
            mRefreshLayout.finishRefresh();

        if (data == null) {
            return;
        }
        int po = 0;
        if (pn == 1) {
            viewBeans.clear();
            adapter.clearTempData();

            if (banner!=null && banner.size()>0) {
                viewBeans.add(new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_TOP_HEIGHT1, banner));
            }
            viewBeans.add(new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_TOP_HEIGHT2));
            if (banner_ad!=null)
                viewBeans.add(new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_TOP_HEIGHT4, banner_ad));
            viewBeans.add(new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_TOP_HEIGHT3));
        } else {
            po = viewBeans.size();
        }

        RecommendV2Adapter.ViewBean lineView = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_LINE_22);

        JumpBaseBean banner = data.getRecommend_banner();
        if (banner != null && banner.getGame_list() != null && banner.getGame_list().size() > 0) {
            if (viewBeans.size() > 0)
                viewBeans.add(lineView);
            RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_CRACK_GAME, banner);
            viewBeans.add(viewBean);
        }

        //分页数据
        List<JumpBaseBean> bannerList = data.getRecommend_banner_list();
        for (int i = 0; bannerList != null && i < bannerList.size(); i++) {
            JumpBaseBean tempBanner = bannerList.get(i);
            if (tempBanner.getGame_list() != null && tempBanner.getGame_list().size() > 0) {
                if (viewBeans.size() > 0)
                    viewBeans.add(lineView);
                if (tempBanner != null && tempBanner.getGame_list() != null && tempBanner.getGame_list().size() > 0) {
                    RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_CRACK_GAME, tempBanner);
                    viewBeans.add(viewBean);
                }
            }
        }

        JumpBaseBean dailyNew = data.getRecommend_edn();
        if (dailyNew != null && dailyNew.getGame_list() != null && dailyNew.getGame_list().size() > 0) {
            if (viewBeans.size() > 0)
                viewBeans.add(lineView);
            RecommendV2Adapter.ViewBean titleView = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_TITLE_ONE, dailyNew);
            viewBeans.add(titleView);
            RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_DAILY_NEW, dailyNew);
            viewBeans.add(viewBean);
        }

        JumpBaseBean gameStarter = data.getRecommend_tf();
        if (gameStarter != null && gameStarter.getGame_list() != null && gameStarter.getGame_list().size() > 0) {
            if (viewBeans.size() > 0)
                viewBeans.add(lineView);
            RecommendV2Adapter.ViewBean titleView = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_TITLE_ONE, gameStarter);
            viewBeans.add(titleView);
            RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_GAME_STARTER, gameStarter);
            viewBeans.add(viewBean);
        }

        JumpBaseBean greatCrack = data.getRecommend_game_list_v1();
        if (greatCrack != null && greatCrack.getGame_list() != null && greatCrack.getGame_list().size() > 0) {
            if (viewBeans.size() > 0)
                viewBeans.add(lineView);
            RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_GREAT_CRACK, greatCrack);
            viewBeans.add(viewBean);
        }

        JumpBaseBean gameHot = data.getNet_hot_game();
        if (gameHot != null && gameHot.getGame_list() != null && gameHot.getGame_list().size() > 0) {
            if (viewBeans.size() > 0)
                viewBeans.add(lineView);
            RecommendV2Adapter.ViewBean titleView = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_TITLE_ONE, gameHot);
            viewBeans.add(titleView);
            RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_GAME_HOT, gameHot);
            viewBeans.add(viewBean);
        }

        JumpBaseBean greatCrackV2 = data.getRecommend_game_list_v2();
        if (greatCrackV2 != null && greatCrackV2.getGame_list() != null && greatCrackV2.getGame_list().size() > 0) {
            if (viewBeans.size() > 0)
                viewBeans.add(lineView);
            RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_GREAT_CRACK, greatCrackV2);
            viewBeans.add(viewBean);
        }

        JumpBaseBean MediaTest = data.getMedia_test();
        if (MediaTest != null && MediaTest.getGame_list() != null && MediaTest.getGame_list().size() > 0) {
            if (viewBeans.size() > 0)
                viewBeans.add(lineView);
            RecommendV2Adapter.ViewBean titleView = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_TITLE_ONE, MediaTest);
            viewBeans.add(titleView);
            RecommendV2Adapter.ViewBean viewBean = new RecommendV2Adapter.ViewBean(RecommendV2Adapter.ViewType.TYPE_GAME_HOT, MediaTest);
            viewBeans.add(viewBean);
        }

        LogUtils.e("tbl>>>po:"+po+",viewBeans.size():"+viewBeans.size());
        if (pn!=1) {
            adapter.notifyItemRangeChanged(po, viewBeans.size());
        } else {
            adapter.notifyDataSetChanged();
        }
        if (refreshLayout != null) {
            if (pn != 1 && (data == null || data.getRecommend_banner_list() == null
                    || data.getRecommend_banner_list().size() == 0)) {
//                refreshLayout.finishLoadMore(300);
//                showToast("╮(๑•́ ₃•̀๑)╭下面~下面~没有了~", 500);
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                if (pn == 1)
                    refreshLayout.finishRefresh();
                else
                    refreshLayout.finishLoadMore();
                pn += 1;
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventMainThread(DownloadEvent downloadEvent) {

        String str = adapter.getPoByGameId(downloadEvent.getGameId());
        if (!StringUtils.isEmpty(str)) {
            GameListBaseBean bean = adapter.getBeanData(Integer.valueOf(str), 0);
            if (bean == null) return;
            DownLoadTaskTable table = bean.getTaskTable();
            if (table == null) {
                table = bean.getDownloadTaskTableSimple();
            }
            table.setDownStatus(downloadEvent.status);
            if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                table.setDownprogress(downloadEvent.getProgress());
            }

            View view = layoutManager.findViewByPosition(Integer.valueOf(str));

            DownloadViewStrokeV2Big dowView = view.findViewById(R.id.itemCrackGameBt);
            if (dowView != null) {
                dowView.updateButn(table);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//订阅
    }
}
